package com.wxn.learncompose.utils

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context.LOCATION_SERVICE
import android.content.pm.PackageManager
import android.location.Criteria
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import androidx.core.app.ActivityCompat
import com.wxn.learncompose.MyApp

/***
 * 需要申请权限： ACCESS_FINE_LOCATION
 */
@SuppressLint("MissingPermission")
suspend fun LocationManager() {
    val lm : LocationManager?  = MyApp.context().getSystemService(LOCATION_SERVICE) as? LocationManager

    val criteria =  Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setAltitudeRequired(false);//不要求海拔
    criteria.setBearingRequired(false);//不要求方位
    criteria.setCostAllowed(true);//允许有花费
    criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗

    val provider:String? = lm?.getBestProvider(criteria, true) //定位的provider

    val location : Location?  = lm?.getLastKnownLocation(provider!!)
    if (location != null) {
        //不为空,显示地理位置经纬度
        val longitude = "Longitude:" + location.getLongitude();
        val latitude = "Latitude:" + location.getLatitude();
    }

    //第二个参数是间隔时间 第三个参数是间隔多少距离，这里我试过了不同的各种组合，能获取到位置就是能，不能获取就是不能
    if (provider != null) {
        lm?.requestLocationUpdates(provider, 3000, 10f, object :LocationListener {
            override fun onLocationChanged(location: Location) {
                //不为空,显示地理位置经纬度
                val longitude = "Longitude:" + location.getLongitude();
                val latitude = "Latitude:" + location.getLatitude();
            }

            override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
                super.onStatusChanged(provider, status, extras)
            }

            override fun onProviderEnabled(provider: String) {
                super.onProviderEnabled(provider)
                //GPS 开启l
            }

            override fun onProviderDisabled(provider: String) {
                super.onProviderDisabled(provider)
                //GPS 关闭了
            }

        })
    };


}
